#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    connect(ui->Calculate,&QPushButton::clicked,this,&Widget::Calculate);
    connect(ui->Export,&QPushButton::clicked,this,&Widget::Export);

    pi=3.14159265;
    gold=0.61803398875;
}

Widget::~Widget()
{
    delete ui;
}

void Widget::Calculate(){

    if (ui->size->text().isEmpty() ||
        ui->num->text().isEmpty()
        ){
        ui->output->setText("未输入完整!");
        return;
    }

    bool isInt;
    v=ui->size->text().toDouble();
    num0=ui->num->text().toInt(&isInt);
    if (!isInt){
        ui->output->setText("矢量数量请输入整数!");
        return;
    }

    num=num0;

    x.resize(num0-1);
    y.resize(num0-1);
    z.resize(num0-1);

    for (int i=0; i<=num0-1 ; ++i){

        deg=2*pi*(i*gold-qFloor(i*gold));

        x[i]=v*((2*i+1)/num-1);
        y[i]=qSqrt(qPow(v,2)-qPow(x[i],2))*qCos(deg);
        z[i]=qSqrt(qPow(v,2)-qPow(x[i],2))*qSin(deg);

    }

    result="";

    for (int i=0; i<=num0-1 ; ++i){
        if (i==num0-1){
            result += QString::number(x[i]) + "\t" + QString::number(y[i]) + "\t" + QString::number(z[i]);
        }else{
            result += QString::number(x[i]) + "\t" + QString::number(y[i]) + "\t" + QString::number(z[i]) + "\n";
        }
    }

    output = "size=" + ui->size->text() + "\t" + "num=" + ui->num->text() + "\n" + "x" + "\t" + "y" + "\t" + "z" + "\n" + result;
    xyz=ui->num->text() + "\n" + "\n" + result;

    ui->output->setText(output);

}

void Widget::Export(){

    QString desktop = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
    savepath= QFileDialog::getSaveFileName(this, tr("Export file, 导出文件"),desktop,"(*.xyz);;(*txt);;All file(*)");

    QFile file(savepath); // 创建文件对象
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) // 打开文件用于写入
    {
        qDebug() << "无法打开文件：" << savepath;
        return;
    }

    QTextStream out(&file); // 创建文本流
    out << xyz; // 将QString写入文件
    file.close(); // 关闭文件

}
